<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use app\api\validate\User;
use think\App;
use think\facade\Db;
use app\common\Baidu;

/**
 * 登录
 * Class Index
 * @package app\api\controller
 */
class Index extends BaseController
{
    protected $weChat;
    protected $JWT;

    public function __construct(App $app)
    {
        $this->model = app('\app\api\model\User');
        $this->weChat = app('\app\common\weChat\WechatMiniLogin');//微信
        $this->JWT = app('\app\api\common\JwtToken');//token配置
        parent::__construct($app);
    }

    /**
     * 获取微信openid
     */
    public function weOpenId()
    {
        $param = get_params();
        try {
            validate(User::class)->scene('getOpenId')->check($param);
            $wechatinfo = $this->weChat->getWeChatInfoByCode($param['code']);
            if ($wechatinfo['code'] != 200) return json(['code' => 400, 'msg' => '未获取到用户openid']);
        } catch (\Exception $e) {    // 验证失败 输出错误信息
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '发送成功', 'data' => $wechatinfo['data']]);
    }



    public function login()
    {
        $param = get_params();
        try {
            validate(User::class)->scene('login')->check($param);
            $phone = $this->weChat->getPhone($param['phone_code']);

            if (!$phone) {
                throw new \Exception('授权失败请重试');
            }
            //判断是登入还是注册
            $user = $this->model->where('mobile', $phone)->find() ?? $this->model;

            //如果用户不存在注册用户
            $userSave = ['open_id' => $param['open_id'], 'mobile' => $phone,'username'=>$phone];
            $user->save($userSave);
            $user_info = $this->model->where('mobile', $phone)->find();
            //生成token
            $user_info['token'] = $this->JWT->getToken($user_info['id']);
            return json(['code' => 200, 'msg' => '登录成功', 'data' => $user_info]);
        } catch (\Exception $exception) {
            return json(['code' => 400, 'msg' => '注册失败' . $exception->getMessage()]);
        }
    }



    public function login_mobile()
    {
        $param = get_params();
        try {
            $phone = $param['phone']??'';

            if (!$phone) {
                throw new \Exception('请填写手机号');
            }

            $code=$param['code']??'';
            if(!$code){
                throw new \Exception('手机验证码不可为空');
            }
            $check_code=Db::name('sms_logs')->where(['status'=>1,'mobile'=>$phone,'checked'=>0])->order('id desc')->find();
            if(!$check_code){
                throw new \Exception('手机验证码错误');
            }
            if($check_code['code']!=$code){
                throw new \Exception('手机验证码错误');
            }
            Db::name('sms_logs')->where('id',$check_code['id'])->update(['checked'=>1,'update_time'=>time()]);
            //判断是登入还是注册
            $user = $this->model->where('mobile', $phone)->find() ?? $this->model;

            //如果用户不存在注册用户
            $userSave = [ 'mobile' => $phone,'username'=>$phone];
            $user->save($userSave);
            $user_info = $this->model->where('mobile', $phone)->find();
            //生成token
            $user_info['token'] = $this->JWT->getToken($user_info['id']);
            return json(['code' => 200, 'msg' => '登录成功', 'data' => $user_info]);
        } catch (\Exception $exception) {
            return json(['code' => 400, 'msg' => '注册失败' . $exception->getMessage()]);
        }
    }






    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function get_user_info()
    {
        $param = [];
        $param['id']=JWT_UID;
        try {
            $user = $this->model->find($param['id']);
        } catch (\Exception $e) {    // 验证失败 输出错误信息
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
        return json(['code' => 200, 'msg' => '成功', 'data' => $user]);
    }

    public function get_qrcode(){
        $uid=JWT_UID;
        $page='pages/home/home';
        $scene="recom_uid=".$uid;
        $res=$this->weChat->get_qrcord_code($scene,$page,'trial');
        return json(['code' => 200, 'msg' => '成功', 'data' => $res]);
    }
















}
